import { useState } from 'react';
import { bool, object, oneOf } from 'prop-types';
import { ReactFlowProvider } from 'reactflow';
import cls from 'classnames';

import type { ReactFlowInstance } from 'reactflow';

import styles from './style.module.less';
// 顶部工具栏
import Header from './Header';
// 侧边栏，展示可拖拽的节点
import Sider from './Sider';
// 画布，处理核心逻辑
import Graph from './Graph';
// 右侧节点配置
import Setting from './Setting';
// 数据流
import { FlowContextProvider } from './context';


ReactFlowApp.propTypes = {
  schema: object,
  backgroundProps: object,
  fitView: bool,
  control: bool,
  readOnly: bool,
  theme: oneOf(['dark', 'light']),
};

function ReactFlowApp(props: any) {
  const {
    schema,
    fitView,
    theme,
    className,
    control,
    thumbnail,
    readOnly,
    backgroundProps,
  } = props;

  /**
   * 保存 ReactFlow 创建后的画布实例
   * 实例会在 Graph 中设置，但会在 Graph 和 Header 中使用，所以将该状态提升到 index.js 中
   */
  const [reactFlowInstance, setReactFlowInstance] = useState<ReactFlowInstance | null>(null);

  const SvgGraph = (
    <FlowContextProvider
      backgroundProps={backgroundProps}
    >
      <Graph
        // 画布，处理核心拖拽逻辑
        instance={reactFlowInstance}
        setInstance={setReactFlowInstance}
        schema={schema}
        fitView={fitView}
        readOnly={readOnly}
        theme={theme}
        control={control}
        className={className}
      />
    </FlowContextProvider>
  );

  if (thumbnail || readOnly) {
    return SvgGraph;
  }

  return (
    <div className={cls('h-full')}>
      <FlowContextProvider
        backgroundProps={backgroundProps}
      >
        <ReactFlowProvider>
          <Header
            // 顶部工具栏
            instance={reactFlowInstance}
          />

          <div className={styles.main}>
            <Sider
              // 左侧边栏，展示可拖拽的节点
            />

            <Graph
              // 画布，处理核心拖拽逻辑
              instance={reactFlowInstance}
              setInstance={setReactFlowInstance}
              schema={schema}
              fitView={fitView}
              readOnly={readOnly}
              theme={theme}
              control={control}
              className={className}
            />

            <Setting
              // Node节点配置
            />
          </div>
        </ReactFlowProvider>

      </FlowContextProvider>
    </div>
  );
}

export default ReactFlowApp;
